package com.sk.weichat.ui.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.RelativeLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.adapter.DynamicLocationAdapter;
import com.sk.weichat.bean.DynamicLoactionBean;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.Call;

import static com.sk.weichat.ui.circle.PublishDynamicActivity.DYNAMIC_SEARCH_LOCATION_INTENT;

/**
 * @Author: chenzl
 * @ClassName: DynamicLocationListActivity
 * @Description: 发布动态 定位 位置列表
 * @CreateDate: 2019/10/23 14:37
 */
public class DynamicLocationListActivity extends BaseActivity {

    private RelativeLayout layout_message_search;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recy_location;

    private List<DynamicLoactionBean.LoactionResult> mDynamicLoactionBean = new ArrayList<>();
    private DynamicLocationAdapter mDynamicLocationAdapter;
    private Double currentLatitude;
    private Double currentLongitude;
    private int mPage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_location_list);
        initActionBar();
        initView();
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView(){
        findViewById(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDynamicLocationAdapter.getPosition()==-1){
                    ToastUtil.showToast(mContext,"请选择所在位置");
                }else {
                    Intent intent = new Intent(DynamicLocationListActivity.this,PublishDynamicActivity.class);
                    intent.putExtra("LoactionResult",mDynamicLoactionBean.get(mDynamicLocationAdapter.getPosition()));
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }
        });

        layout_message_search = findViewById(R.id.layout_message_search);
        layout_message_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DynamicLocationListActivity.this,SearchLocationListActivity.class),DYNAMIC_SEARCH_LOCATION_INTENT);
            }
        });
        recy_location = findViewById(R.id.recy_location);
        recy_location.setLayoutManager(new LinearLayoutManager(this));
        mDynamicLocationAdapter = new DynamicLocationAdapter(mDynamicLoactionBean);
        mDynamicLocationAdapter.setHasStableIds(true);
        recy_location.setAdapter(mDynamicLocationAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_location.getItemAnimator()).setSupportsChangeAnimations(false);

        refreshLayout = findViewById(R.id.refresh_search_location);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.setNoMoreData(false);
                mPage = 0;
                LoadLoaction(currentLatitude,currentLongitude,mPage,false);

            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                LoadLoaction(currentLatitude,currentLongitude,mPage,false);

            }
        });
        currentLatitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        currentLongitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        LoadLoaction(currentLatitude,currentLongitude,mPage,true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode==DYNAMIC_SEARCH_LOCATION_INTENT){
                setResult(RESULT_OK,data);
                finish();
            }
        }
    }

    /**
     * @author: czl
     * @description 加载当前 附近位置
     * @date: 2019/10/23 17:05
     */
    private void LoadLoaction(double latitude,double longitude,int pageNum,boolean isShow){
        if (isShow){
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("latitude", String.valueOf(latitude));
        params.put("longitude", String.valueOf(longitude));
        params.put("radius", "2000");
        params.put("pageIndex", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(20));

        HttpUtils.post().url(coreManager.getConfig().MAP_PLACE_SEARCH)
                .params(params)
                .build()
                .execute(new BaseCallback<DynamicLoactionBean>(DynamicLoactionBean.class) {

                    @Override
                    public void onResponse(ObjectResult<DynamicLoactionBean> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            refreshLayout.setVisibility(View.VISIBLE);
                            List<DynamicLoactionBean.LoactionResult> datas = result.getData().getResults();
                            if (mPage == 0) {
                                refreshLayout.finishRefresh();
                                mDynamicLoactionBean.clear();
                            } else if(datas.size() == 10){
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }else{
                                refreshLayout.finishLoadMore();
                            }
                            if (mPage==0){
                                DynamicLoactionBean.LoactionResult mLoactionResult = new DynamicLoactionBean.LoactionResult();
                                mLoactionResult.setName("不显示位置");
                                mDynamicLoactionBean.add(0,mLoactionResult);
                            }
                            mDynamicLoactionBean.addAll(datas);
                            mDynamicLocationAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(DynamicLocationListActivity.this, e.getMessage());
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
